package in.srain.cube.request;

import java.io.Serializable;

public abstract class RequestBase<T, OriginDataType> implements IRequest<T, OriginDataType>, Serializable {

    private RequestData mRequestData = new RequestData();
    private FailData mFailData;
    private boolean mHasBeenCanceled = false;
    private boolean mPostToMainThread = true;

    final public boolean isPostToMainThread() {
        return mPostToMainThread;
    }

    final public void setPostToMainThread(boolean postToMainThread) {
        mPostToMainThread = postToMainThread;
    }

    public RequestData getRequestData() {
        return mRequestData;
    }

    @Override
    public void send() {
        prepareRequest();
        doSendRequest();
    }

    @Override
    public T requestSync() throws Throwable {
        prepareRequest();
        return doRequestSync();
    }

    @Override
    public void cancelRequest() {
        mHasBeenCanceled = true;
        onCancel();
    }

    @Override
    public T onDataFromServer(OriginDataType originData) {
        return processOriginDataFromServer(originData);
    }

    protected boolean hasBeenCanceled() {
        return mHasBeenCanceled;
    }

    protected void onCancel() {
    }

    @Override
    public FailData getFailData() {
        return mFailData;
    }

    @Override
    public RequestBase setFailData(FailData failData) {
        mFailData = failData;
        return this;
    }

    /**
     * implement this method to process request data
     */
    protected abstract void doSendRequest();

    /**
     * implement this method to request data synchronously
     */
    protected abstract T doRequestSync() throws Throwable;

    /**
     * prepare request
     */
    protected abstract void prepareRequest();
}
